from __future__ import absolute_import
from os.path import join
from forest.api import Command, get_tool

class InstallBootloader(Command):
    ''' Sets up the bootloader on the disks specified by the bootloader resource.

    '''
    __register__ = 'commands.install.InstallBootloader'

    def run(self, config):
        install_disks = []

        bootloaders = list(config.get_resources().iter_by_type('bootloader'))

        if not bootloaders:
            return

        for bootloader in bootloaders:
            devices = bootloader.get_device()

            if isinstance(devices, list):
                install_disks.extend(devices)
            else:
                install_disks.append(devices)

        #boot_mount = args.get('boot_fs', ['/mnt/install/boot'])
        installroot = config.get_install_root()

        # drives_file = open('/proc/partitions', 'r')
        get_tool('system.mount')('none', join(installroot, 'proc'), 'proc')
        get_tool('system.bindmount')('/dev', join(installroot, 'dev'))
        get_tool('system.bindmount')('/sys', join(installroot, 'sys'))

        grubdefaults = join(installroot, 'etc', 'default','grub')

        get_tool('files.write')(grubdefaults,
                'GRUB_PRELOAD_MODULES="mdadm1x mdadm09 raid ext3 part_gpt part_msdos"\n',
                mode = 'a')

        kernelsysconfig = join(installroot, 'etc', 'sysconfig','kernel')
        get_tool('files.write')(kernelsysconfig,
                'UPDATEDEFAULT=yes\n'
                'DEFAULTKERNEL=kernel\n', mode = 'w')

        with get_tool('system.chroot')(installroot):
            get_tool('system.execute')(['grub2-mkconfig', '-o', '/boot/grub2/grub.cfg'])

        # write mdadm conf and rebuild initrd with md support
        if config.get('raid', False):
            with get_tool('system.chroot')(installroot):
                get_tool('system.execute')(['dracut', '--force', '--mdadmconf', '--fstab'])

            mdadm_conf = get_tool('raid.get_mdadmconf')()
            with get_tool('system.chroot')(installroot):
                get_tool('files.write')('/etc/mdadm.conf', mdadm_conf)

        for disk in install_disks:
            with get_tool('system.chroot')(installroot):
                args  = ['grub2-install', '--force', '/dev/%s' % disk]
                for line in get_tool('system.poll')(args):
                    print line

